import type { MicroAppConfig, MicroAppStateActions } from 'qiankun';

// 创建支持哈希模式和历史模式的激活规则函数
export function createActiveRule(prefix: string) {
  return (location: Location) => {
    // 检查是否是哈希模式
    const isHashMode = location.hash && process.env.NODE_ENV === 'development';
    if (isHashMode) {
      // 哈希模式：检查 # 后面的路径是否以 prefix 开头
      return location.hash.startsWith(`#${prefix}`);
    } else {
      // 历史模式：直接检查路径
      return location.pathname.startsWith(prefix);
    }
  };
}

export const MICRO_APPS = [
  {
    name: 'micro-auth',
    entry: process.env.NODE_ENV === 'production' ? '/micro-apps/auth/' : '//localhost:5002',
    container: '#micro-container',
    activeRule: createActiveRule('/micro-auth'),
    order: 1
  },
  {
    name: 'micro-dashboard',
    entry: process.env.NODE_ENV === 'production' ? '/micro-apps/dashboard/' : '//localhost:5003',
    container: '#micro-container',
    activeRule: createActiveRule('/micro-dashboard'),
    order: 0
  },
  {
    name: 'micro-user',
    entry: process.env.NODE_ENV === 'production' ? '/micro-apps/user/' : '//localhost:5004',
    container: '#micro-container',
    activeRule: createActiveRule('/micro-user'),
    order: 2
  },
  {
    name: 'legacy-vue2-app',
    entry: 'https://vue.ruoyi.vip', // 统一使用代理路径
    container: '#micro-container',
    activeRule: createActiveRule('/index'),
    order: 3
  }
];

/**
 * 微应用配置类型
 */
export interface EnhancedMicroAppConfig extends MicroAppConfig {
  // 微应用的名称
  name: string;
  // 微应用的入口URL
  entry: string;
  // 微应用的挂载容器
  container: string;
  // 微应用的激活规则
  activeRule: string | string[];
  // 微应用的加载顺序，数字越小越先加载
  order?: number;
  // 是否启用沙箱隔离
  sandbox?: boolean;
  // 微应用的自定义属性
  props?: Record<string, any>;
}

/**
 * 创建微应用配置
 * @param config 微应用基础配置
 * @param globalStateActions 全局状态管理实例
 * @returns 增强的微应用配置
 */
export function createMicroAppConfig(
  config: Omit<EnhancedMicroAppConfig, 'props'>,
  globalStateActions: MicroAppStateActions
): EnhancedMicroAppConfig {
  return {
    ...config,
    props: {
      ...config.props,
      onGlobalStateChange: globalStateActions.onGlobalStateChange,
      setGlobalState: globalStateActions.setGlobalState,
      // 可以在这里添加其他共享属性
      appInfo: {
        name: config.name,
        entry: config.entry,
        activeRule: config.activeRule
      }
    },
    // 配置沙箱，启用严格的样式隔离
    sandbox: config.sandbox !== false ? {
      // 启用严格样式隔离
      strictStyleIsolation: true,
      // 实验性样式隔离（可选）
      experimentalStyleIsolation: true
    } : false
  };
}

/**
 * 微应用配置列表
 * @param globalStateActions 全局状态管理实例
 * @returns 微应用配置数组
 */
export function getMicroAppsConfig(globalStateActions: MicroAppStateActions): EnhancedMicroAppConfig[] {
  return MICRO_APPS.map(app => createMicroAppConfig(app as any, globalStateActions));
}

/**
 * 获取微应用生命周期钩子配置
 * @returns 微应用生命周期钩子
 */
export function getMicroAppsLifeCycles() {
  return {
    beforeLoad: [
      (app: EnhancedMicroAppConfig) => {
        console.log('[LifeCycle] before load %c%s', 'color: green;', app.name);
      }
    ],
    beforeMount: [
      (app: EnhancedMicroAppConfig) => {
        console.log('[LifeCycle] before mount %c%s', 'color: green;', app.name);
      }
    ],
    afterUnmount: [
      (app: EnhancedMicroAppConfig) => {
        console.log('[LifeCycle] after unmount %c%s', 'color: green;', app.name);
      }
    ]
  };
}

/**
 * 获取默认挂载的微应用名称
 * @returns 默认微应用名称
 */
export function getDefaultMicroAppName(): string {
  return 'micro-dashboard';
}